package edu.njucm.herbiv.config

import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import java.io.File
import kotlin.io.path.Path
import kotlin.io.path.absolute
import kotlin.io.path.createDirectories
import kotlin.io.path.exists

private val logger = KotlinLogging.logger { }
/**
 * @Author ZhouHang
 * @Date 24/5/21 周二
 */
@Configuration
class WebMVCConfig @Autowired constructor(
    val applicationProperties: ApplicationProperties
): WebMvcConfigurer {

    override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
        // 测试 HERBIV_HOME 环境变量是否存在
        val herbivHome = System.getenv("HERBIV_HOME")
        if (herbivHome == null) {
            logger.error { "请配置环境变量 HERBIV_HOME" }
            throw RuntimeException("找不到环境变量 HERBIV_HOME")
        }
        logger.info { "HERBIV_HOME: $herbivHome" }
        // 配置本地存储数据路径
        val dataDir = Path(applicationProperties.locPath)
        if (!dataDir.exists()) {
            dataDir.createDirectories()
            logger.info { "成功创建数据存储目录：${applicationProperties.locPath}" }
        }
        logger.info { "数据存储目路径: ${dataDir.toAbsolutePath()}" }
        registry
            .addResourceHandler(applicationProperties.reqPath)
            .addResourceLocations("file:" + dataDir.toAbsolutePath() + File.separator)
    }

    override fun addCorsMappings(registry: CorsRegistry) {
        registry
            .addMapping("/**")        // 允许跨域的路径
//            .allowedOrigins("*")        // 允许跨域请求的域名
//            .allowedMethods("*")       // 允许跨域的方法
//            .allowCredentials(false)            // 是否允许证书
//            .allowedHeaders("token")   // 允许的 Header 属性
//            .maxAge(3600)                       // 跨域允许的时间
    }
}
